package com.seo.proxy;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

public class Blacklist {

	private final Logger LOGGER = Logger.getLogger(getClass());
	
	private File file = new File("blacklist");
	
	private long lastReadTime = 0;

	private Set<String> blacklist = new HashSet<String>();

	public Blacklist() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (;;) {
					try {
						read();
						Thread.sleep(1000);
					} catch (Exception e) {
						LOGGER.error(e.getMessage(), e);
					}
				}
			}
		}).start();
	}

	private void read() throws IOException {
		if (file.isFile() && file.lastModified() > lastReadTime) {
			blacklist = new HashSet<String>(FileUtils.readLines(file));
			LOGGER.info("Added " + blacklist.size() + " to blacklist");
			lastReadTime = file.lastModified();
		}
	}

	public boolean isBlacklisted(String url) {
		for (String sign : blacklist) {
			if (!sign.isEmpty() && url.toLowerCase().contains(sign)) {
				return true;
			}
		}
		return false;
	}

}
